package xyz.shenmegui.foodcheckserver.resolver;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import xyz.shenmegui.foodcheckserver.DO.User;
import xyz.shenmegui.foodcheckserver.annotation.LoginUser;
import xyz.shenmegui.foodcheckserver.service.UserService;
import xyz.shenmegui.foodcheckserver.utils.ObjectUtil;

@Component
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private UserService userService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(User.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

        Object object = webRequest.getAttribute("userid", RequestAttributes.SCOPE_REQUEST);
//        System.out.println("LoginUserHandlerMethodArgumentResolver--userid:" + object);
        if (ObjectUtil.isNull(object)) {
            return null;
        }
        return userService.getUserById((int) object);
    }
}
